package com.wn.common.net.config

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * @Author: wn
 * @Date: 2023/2/9 16:05
 * @Description: 重试请求拦截器
 * maxRetry重试次数
 */

class RetryInterceptor(private val maxRetry: Int = 0) : Interceptor {
  // 已经重试的次数,注意，设置maxRetry重试次数，作用于重试，所以总的请求次数，可能就是原始的1，+ maxRetry
  private var retriedNum: Int = 0

  override fun intercept(chain: Interceptor.Chain): Response {
    val request: Request = chain.request()
    Log.d("RetryInterceptor", "intercept 29行: 当前retriedNum=$retriedNum")
    // 调用
    var response = chain.proceed(request)
    while (!response.isSuccessful && retriedNum < maxRetry) {
      retriedNum++
      Log.d("RetryInterceptor", "intercept 33行: 当前retriedNum=$retriedNum")
      // 再次调用
      response.close() //报错后 添加
      response = chain.proceed(request)
    }
    // 返回出去
    return response
  }
}